package cn.itcast.protocol.testCodeC;

import cn.itcast.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

/**
 * @ClassName MessageCodec
 * @Description MessageCodec
 * @Author tant
 * @Date 2025/1/21 10:47
 */
@Slf4j
//@ChannelHandler.Sharable
public class MessageCodec extends ByteToMessageCodec<Message> {

    @Override
    public void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        out.writeBytes(new byte[]{1, 2, 3, 4});//魔术  -4byte
        out.writeByte(1);//版本                   -1byte
        out.writeByte(0);// 序列化方式 jdk 0,json 1   -1byte
        out.writeByte(msg.getMessageType());//指令类型/消息类型  -1byte
        out.writeInt(msg.getSequenceId());//序列号   -4byte
        out.writeByte(0xff);// -1byte(对齐 一般推荐2的幂次方)
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(bos);
        os.writeObject(msg);
        byte[] byteArray = bos.toByteArray();
        out.writeInt(byteArray.length);//长度  -4byte
        out.writeBytes(byteArray);//内容
    }


    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int magicNum = in.readInt(); //魔数
        byte version = in.readByte(); //版本
        byte serializerType = in.readByte(); //序列化方式
        byte messageType = in.readByte(); //消息类型
        int sequenceId = in.readInt(); //序列号
        in.readByte(); //对齐填充
        int length = in.readInt(); //内容长度
        byte[] bytes = new byte[length];
        in.readBytes(bytes, 0, length); //内容
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        Message message = (Message) ois.readObject();
        log.debug("{}, {}, {}, {}, {}, {}", magicNum, version, serializerType, messageType, sequenceId, length);
        log.debug("{}", message);
        out.add(message);
    }

}

    